package org.ourgrid.worker.collectors.gmond;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class GMondUtilsWindows extends GMondUtils {

	@Override
	public int getGmondPort(String configFile) throws GMondCollectorException {
		Scanner sc;
		try {
			sc = new Scanner(new BufferedReader(
					new FileReader("C:\\Arquivos de programas\\ganglia\\gmond\\gmond.conf")));
		} catch (FileNotFoundException e) {
			throw new GMondCollectorException("Could not find gmond configuration file.");
		}
		while(sc.hasNext()) {
			if( sc.next().startsWith("tcp_accept_channel") ) {
				while(! sc.next().equals("port") ) {}
				sc.next(); // equals simbol
				return Integer.parseInt(sc.next());
			}
		}
		
		return -1;
	}

	/**
	 * implemented
	 */
	public boolean isGMondInstalled() {
		File gmondExecutableFile = new File("C:\\Arquivos de programas\\ganglia\\gmond\\gmond.exe");
		return gmondExecutableFile.exists();
	}

	/**
	 * implemented
	 */
	public boolean isGMondRunning() throws IOException {
		String command = "net start";
		Process process = Runtime.getRuntime().exec(command);
		Scanner sc = new Scanner(process.getInputStream());
		
		int count = 0;
		while(sc.hasNextLine()) {
			String line = sc.nextLine();
			if(line.indexOf("gmond") >= 0)
				count++;
		}

		return count > 0;
	}
	

	protected void startGMondDaemon() throws IOException {
		String command = "net start gmond";
		Runtime.getRuntime().exec(command);
	}

	public void stopGMond() throws IOException {
		String command = "net stop gmond";
		Runtime.getRuntime().exec(command);		
	}

	public String getGmondAddress() throws GMondCollectorException {
		return "127.0.0.1";
	}

	@Override
	public String getGmondConfigFile() {
		return "C:\\Arquivos de programas\\ganglia\\gmond\\gmond.conf";
	}

}
